Page({
  data: {
    socketOpen: false,
    inputMsg: '',
    messages: [],
    scrollTop: 0,  // 保持与网络界面相同的滚动控制
    loading: false
  },

  sendMessage() {
    const msg = this.data.inputMsg.trim();
    if (!msg || this.data.loading) return;

    // 添加用户消息（保持与网络界面相同的结构）
    this.addMessage(msg, true);
    this.setData({ inputMsg: '', loading: true });

    wx.request({
      url: 'https://api.deepseek.com/v1/chat/completions',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer sk-8d1b4abc924c45ad8ee63d37d1e95c9c'
      },
      data: {
        model: "deepseek-chat",
        messages: [
          { role: "system", content: "You are a helpful assistant" },
          { role: "user", content: msg }
        ],
        stream: false
      },
      success: res => {
        const reply = res.data.choices[0].message.content;
        this.addMessage(reply, false); // 添加AI回复
      },
      fail: err => {
        console.error('请求失败:', err);
        this.addMessage('对话服务暂时不可用', false); // 错误提示样式与接收消息一致
      },
      complete: () => this.setData({ loading: false })
    });
  },

  // 统一消息添加方法（适配新UI）
  addMessage(content, isSent) {
    const newMessage = {
      content: content,
      isSent: isSent  // 保持与网络界面相同的字段
    };
    
    this.setData({
      messages: [...this.data.messages, newMessage],
      scrollTop: this.data.messages.length * 10000  // 保持与网络界面相同的滚动逻辑
    }, () => {
      setTimeout(() => {
        this.setData({
          scrollTop: this.data.scrollTop + 1
        })
      }, 50);
    });
  },

  onInput(e) {
    this.setData({ inputMsg: e.detail.value });
  }
});
